<?php

class ReviewForm extends CFormModel
{
	public $uid;
	public $place_id;
	public $text;
	public $rate;
	
	private $review;
	
	const ERROR_HAS_REVIEW = 1;
	
	public function rules()
	{
		return array(
			array('uid, place_id, text, rate', 'required'),
		);
	}
	
	public function addReview()
	{
		if($this->hasReview($this->uid) != null){
			$this->addErrors(array(
				'review'=>array('message'=> 'คุณได้รีวิวไปก่อนหน้านี้แล้ว', 'code'=> self::ERROR_HAS_REVIEW))
			);
			return false;
		}
		$review = new Review();
		$review->attributes = $this->attributes;
		if($review->save())
		{
			$this->review = Review::model()->with('account')->findByPk($review->id);
			return true;
		}
		return false;
	}
	
	public function getReview()
	{
		return $this->review;
	}
	
	public function hasReview($uid)
	{
		$review = Review::model()->findByAttributes(array('place_id'=>$this->place_id, 'uid'=>$this->uid));
		return $review;
	}
}